package com.hmall.common.config;

import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

// 配置类，用于定义错误消息处理相关的Bean
@Configuration
// 条件注解，只有当配置属性spring.rabbitmq.listener.simple.retry.enabled为true时，该配置类才会生效
@ConditionalOnProperty(name = "spring.rabbitmq.listener.simple.retry.enabled", havingValue = "true")
// 使用Lombok注解，自动生成构造函数，包含所有final类型的成员变量
@RequiredArgsConstructor
public class MqConsumeErrorAutoConfiguration {
    // 注入RabbitTemplate，用于消息的发送
    private final RabbitTemplate rabbitTemplate;

    //获取当前微服务名
    @Value("${spring.application.name}")
    private String serviceName;

    //声明误消息交换机
    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange("error.exchange");
    }
    //声明错误消息队列
    @Bean
    public Queue errorQueue(){
        return new Queue(serviceName+".error.queue",  true);
    }
    //声明错误消息绑定上述的交换机和队列
    @Bean
    public Binding errorBinding(DirectExchange directExchange,  Queue errorQueue){
        return BindingBuilder.bind(errorQueue).to(directExchange).with(serviceName+".error");
    }
    //声明失败消息处理(核心)
    @Bean
    public MessageRecoverer messageRecoverer(RabbitTemplate rabbitTemplate){
        return new RepublishMessageRecoverer(rabbitTemplate, "error.exchange", serviceName+".error");
    }
}
